#include "pch.h"
#include "CCjs.h"


void  CheckThrow(JsErrorCode errorCode)
{
	if (JsNoError != errorCode)
	{
		throw ChakraErrorException(errorCode);
	}
}

JsValueRef  Vconvert(std::wstring var) {
	JsValueRef resutl = nullptr;
	JsPointerToString(var.data(), var.size(), &resutl);
	return resutl;
}

JsValueRef  Vconvert(std::string var) {

	auto wvar = string_convert::ANSIToUnicode(var.c_str());
	JsValueRef resutl = nullptr;
	JsPointerToString(wvar.data(), wvar.size(), &resutl);
	return resutl;
}

JsValueRef  Vconvert(int var) {
	JsValueRef resutl = nullptr;
	JsIntToNumber(var, &resutl);
	return resutl;
}

void CCJs::RunScript(_In_z_ const wchar_t* script) {
	CheckThrow(JsRunScript(script, _currentSourceContext++, L"", NULL));
}


JsValueRef CCJs::GetObjectAsProperty(_In_z_ const wchar_t* funcname) {
	JsPropertyIdRef propertyId;
	CheckThrow(JsGetPropertyIdFromName(funcname, &propertyId));

	JsValueRef 	 result;
	CheckThrow(JsGetProperty(_globalObject, propertyId, &result));
	return result;
}
JsContextRef CCJs::GetContext() {
	return _context;
}
JsContextRef CCJs::GetGlobal() {
	return _globalObject;
}


std::wstring LoadFile(const wchar_t* n) {
	auto file = CreateFile(n, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (file == (HANDLE)-1)
	{
		assert(0);
	}
	auto size = GetFileSize(file, NULL);
	if (size <= NULL)
	{
		return L"";
	}
	std::shared_ptr<char> buffer(new char[size + 2]);
	ZeroMemory(buffer.get(), size + 2);
	DWORD readlen = 0;
	ReadFile(file, buffer.get(), size, &readlen, NULL);
	CloseHandle(file);
	std::string r(buffer.get());

	return 	string_convert::ANSIToUnicode(r.c_str());
}

